package com.wenruo.funycollecte.util;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Iterator;
import java.util.Map;

import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.Bitmap.Config;
import android.util.Log;
import android.widget.ImageView;

import com.android.volley.Request.Method;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.Response.ErrorListener;
import com.android.volley.Response.Listener;
import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.ImageRequest;
import com.android.volley.toolbox.ImageLoader.ImageListener;
import com.android.volley.toolbox.Volley;
import com.wenruo.funycollecte.R;

public class Client {

	private static final String HOST = "http://10.205.48.99:8080/";
	private static final String LIST_ITEM = HOST + "item/list.json";
	private static final String FETCH_UPDATE = HOST + "item/fetchUpate.json";
	private static RequestQueue mQueue;
	private static BitmapLruCache mBitmapLruCache;
	private static DiskLruImageCache mDiskLruImageCache;
	
	public static void init() {
		mQueue = Volley.newRequestQueue(ContextUtil.getApplicationContext());
		mBitmapLruCache = new BitmapLruCache();
		mDiskLruImageCache = new DiskLruImageCache(ContextUtil.getApplicationContext(), "funy", 10 * 1024 * 1024, CompressFormat.JPEG, 100);
	}
	
	public static void listItem(Map<String, String> params, Listener<ResponseEntity> listener, ErrorListener errorListener) {
		StringBuilder url = new StringBuilder(LIST_ITEM);
		url.append("?").append(URLEncode(params));
		Log.i("url", url.toString());
		JsonRequest<ResponseEntity> jsonRequest = new JsonRequest<>(Method.GET, url.toString(), params, ResponseEntity.class, listener, errorListener);
		mQueue.add(jsonRequest);
	}
	
	public static void fetchUpdate(Map<String, String> params, Listener<ResponseEntity> listener, ErrorListener errorListener) {
		StringBuilder url = new StringBuilder(FETCH_UPDATE);
		url.append("?").append(URLEncode(params));
		Log.i("url", url.toString());
		JsonRequest<ResponseEntity> jsonRequest = new JsonRequest<>(Method.GET, url.toString(), null, ResponseEntity.class, listener, errorListener);
		mQueue.add(jsonRequest);
	}
	
	public static void fetchImage(String url, final ImageView imageView) {
		imageView.setImageResource(R.drawable.default_image);
		final String key = hashKeyForDisk(url);
		Bitmap bitmap = mBitmapLruCache.get(key) != null ? mBitmapLruCache.get(key) : mDiskLruImageCache.getBitmap(key);
				
		if (bitmap == null) {
			ImageRequest imageRequest = new ImageRequest(
					url,
					new Response.Listener<Bitmap>() {
						@Override
						public void onResponse(Bitmap response) {
							mBitmapLruCache.put(key, response);
							mDiskLruImageCache.put(key, response);
							imageView.setImageBitmap(response);
						}
					}, 0, 0, Config.ARGB_8888, new Response.ErrorListener() {
						@Override
						public void onErrorResponse(VolleyError error) {
							imageView.setImageResource(R.drawable.failed_image);
						}
					});
			mQueue.add(imageRequest);
		} else {
			imageView.setImageBitmap(bitmap);
		}

	}
	
	public static String URLEncode(Map<String, String> params) {
		StringBuilder sb = new StringBuilder();
		Iterator<String> itr = params.keySet().iterator();
		while (itr.hasNext()) {
			String key = itr.next();
			sb.append("&")
			  .append(key)
			  .append("=")
			  .append(params.get(key));
		}
		return sb.toString();
	}
	
	/**
	 * 使用MD5算法对传入的key进行加密并返回。
	 */
	public static String hashKeyForDisk(String key) {
		String cacheKey;
		try {
			final MessageDigest mDigest = MessageDigest.getInstance("MD5");
			mDigest.update(key.getBytes());
			cacheKey = bytesToHexString(mDigest.digest());
		} catch (NoSuchAlgorithmException e) {
			cacheKey = String.valueOf(key.hashCode());
		}
		return cacheKey;
	}
	
	public static String bytesToHexString(byte[] bytes) {
		StringBuilder sb = new StringBuilder();
		for (int i = 0; i < bytes.length; i++) {
			String hex = Integer.toHexString(0xFF & bytes[i]);
			if (hex.length() == 1) {
				sb.append('0');
			}
			sb.append(hex);
		}
		return sb.toString();
	}
}
